<template>
  <view class="body">
    <up-steps class="steps-x" :current="state.steps" activeColor="#00D1B6" inactiveColor="#999999">
      <up-steps-item title="基本信息" />
      <up-steps-item title="生活习惯" />
      <up-steps-item title="健康情况" />
    </up-steps>
    <!-- 第一步 -->
    <view v-if="state.steps == 0" class="base_info">
      <view class="topic">
        请填写您的真实情况，我们将根据您的情况为您制定个性化的体重管理方案
      </view>
      <view v-if="state.questionList.length > 0" class="baseInfoBox">
        <view class="box_title">{{ state.questionList[0].name }}</view>
        <view class="cell">
          <view class="left">用户</view>
          <view class="right">
            {{ userInfo.patientInfo.patName }}&nbsp;&nbsp;
            {{ userInfo.patientInfo.gender }}&nbsp;&nbsp; {{ userInfo.patientInfo.age }}岁
          </view>
        </view>
        <view v-for="(item, index) of state.questionList[0].list" :key="index" class="cell">
          <view class="left">{{ item.questionName }}</view>
          <view class="right">
            <input
              class="form_input"
              type="digit"
              v-model="item.inputText"
              placeholder="请输入"
              @blur="numberfixed(item)"
              :border="false"
            />
            <text>{{
              item.questionName == '当前体重' || item.questionName == '目标体重' ? 'kg' : 'cm'
            }}</text>
          </view>
        </view>
      </view>
    </view>
    <!-- 第二步 -->
    <view v-if="state.steps == 1" class="base_info">
      <view class="baseInfoBox">
        <view class="box_title">{{ state.questionList[1].name }}</view>
        <view v-for="(item, index) of state.questionList[1].list" :key="index" class="question">
          <view class="question_title">{{ item.questionName }}</view>
          <view class="answer">
            <view
              v-for="(i, idx) of item.options"
              :key="idx"
              @click="select(i, item)"
              :class="[
                'answer_item',
                i.check ? 'on' : '',
                i.long ? 'w100' : '',
                i.disabled ? 'disabled' : ''
              ]"
            >
              {{ i.label }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 第三步 -->
    <view v-if="state.steps == 2" class="base_info">
      <view class="baseInfoBox">
        <view class="box_title">{{ state.questionList[2].name }}</view>
        <view v-for="(item, index) of state.questionList[2].list" :key="index" class="question">
          <view class="question_title"
            ><view v-if="item.questionType == '多选'" class="isMore">多选</view
            >{{ item.questionName }}</view
          >
          <view class="answer">
            <view
              v-for="(i, idx) of item.options"
              :key="idx"
              @click="select(i, item)"
              :class="['answer_item', i.check ? 'on' : '', i.long ? 'w100' : '']"
            >
              {{ i.label }}
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="fixed">
      <button v-if="state.steps != 0" class="pre_btn" @tap="prev()">上一步</button>
      <button v-if="state.steps != 2" class="next_btn" @tap="next()">下一步</button>
      <button v-if="state.steps == 2" class="next_btn" @tap="next()">确认提交</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, watch, nextTick } from 'vue'
import { new_question, weight_save } from '@/api/questionaire'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy } from '@/utils/tools'
import { formatDate } from '@/utils/util'
import store from '@/store'

const state = reactive({
  steps: 0,
  questionList: [],
  questionInfo: {}
})
const userInfo = ref({})

let currentId = ''

onShow(() => {
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
    currentId = deepCopy(userInfo.value.patientInfo.empi)
    // currentId = '74567895'
    init()
  }
  if (userInfo.value.patientInfo.age < 6) {
    uni.showModal({
      title: '提示',
      content: '当前用户年龄过小，不建议使用体重管理服务，请选择其他用户',
      showCancel: false,
      confirmText: '回到首页',
      success: (res) => {
        if (res.confirm) {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }
    })
  }
})

const init = () => {
  const params = { clientId: 2, empi: currentId }
  new_question(params).then((res) => {
    state.questionList = JSON.parse(res.data.content)
    state.questionInfo = res.data
    state.questionList.forEach((item: any) => {
      item.list.forEach((val: any) => {
        if (
          val.options &&
          val.options.length > 0 &&
          val.options.some((i: any) => {
            return i.value.length > 8
          })
        ) {
          val.options.forEach((i: any) => {
            i.long = true
          })
        }
      })
    })
    console.log('题目列表', state.questionList)
  })
}

const numberfixed = (item: any) => {
  const textArr = String(item.inputText).split('.')
  if (textArr.length > 1 && textArr[1].length > 1) {
    item.inputText = Number(Number(textArr[0] + '.' + textArr[1]).toFixed(1))
  }
  if (item.questionName == '身高') {
    if (item.inputText > 250) {
      item.inputText = 250
    }
  } else {
    if (item.inputText > 200) {
      item.inputText = 200
    }
  }
}

const select = (item: any, val: any) => {
  // item为选项信息，val为题目信息
  if (item.disabled) {
    return
  }
  if (val.questionType == '单选') {
    // 单选逻辑
    val.options.forEach((i) => {
      i.check = false
    })
    val.value = item.value
    val.option = item.id
    val.scores = item.score
    if (item.value == '从不运动') {
      state.questionList[1].list[3].options.forEach((answer: any) => {
        answer.disabled = true
        answer.check = false
      })
      state.questionList[1].list[3].value = ''
      state.questionList[1].list[3].option = ''
      state.questionList[1].list[3].scores = 0
    }
    if (state.questionList[1].list[2].value != '从不运动') {
      state.questionList[1].list[3].options.forEach((answer: any) => {
        answer.disabled = false
      })
    }
  } else {
    // 多选逻辑
    if (!val.value || val.value.length == 0) {
      val.value = item.value
      val.option = String(item.id)
      val.scores = item.score
    } else {
      // 第二次以后选中
      if (!item.check) {
        if (item.value == '以上都没有' || val.value.includes('以上都没有')) {
          val.value = item.value
          val.option = String(item.id)
          val.scores = item.score
          val.options.forEach((v: any) => {
            v.check = false
          })
        } else {
          val.value = val.value + ',' + item.value
          val.option = val.option + ',' + item.id
          val.scores += item.score
        }
      } else {
        // 重复点击取消选中
        val.value = val.value.replace(item.value + ',', '')
        val.value = val.value.replace(',' + item.value, '')
        val.value = val.value.replace(item.value, '')
        val.option = val.option.replace(item.id + ',', '')
        val.option = val.option.replace(',' + item.id, '')
        val.option = val.option.replace(item.id, '')
        val.scores -= item.score
      }
    }
  }
  item.check = !item.check
}

const prev = () => {
  state.steps--
}
const next = () => {
  let canGoNext = true
  if (state.steps === 0) {
    const regex = /\..*\./
    const result1 = regex.test(String(state.questionList[0].list[0].inputText))
    const result2 = regex.test(String(state.questionList[0].list[1].inputText))
    const result3 = regex.test(String(state.questionList[0].list[2].inputText))
    const result4 = regex.test(String(state.questionList[0].list[3].inputText))
    const result5 = regex.test(String(state.questionList[0].list[4].inputText))
    if (result1 || result2 || result3 || result4 || result5) {
      uni.showToast({
        title: '基本信息格式有误，请输入正确格式',
        icon: 'none'
      })
      return
    } else if (
      Number(state.questionList[0].list[2].inputText) >
      Number(state.questionList[0].list[1].inputText)
    ) {
      uni.showToast({
        title: '目标体重需小于当前体重',
        icon: 'none'
      })
      return
    }
    // 第一步
    state.questionList[0].list.forEach((item) => {
      if (item.inputText == '') {
        canGoNext = false
      }
    })
  } else if (state.steps === 1) {
    // 第二步
    state.questionList[state.steps].list.forEach((item) => {
      if (item.inputText == '' && (item.value == '' || item.value.length == 0)) {
        canGoNext = false
      }
    })
    // 从不运动个性化处理
    if (
      state.questionList[1].list[3].value == '' &&
      state.questionList[1].list[2].value == '从不运动'
    ) {
      canGoNext = true
    }
  } else {
    // 第三步
    state.questionList[state.steps].list.forEach((item) => {
      if (item.inputText == '' && (item.value == '' || item.value.length == 0)) {
        canGoNext = false
      }
    })
  }
  if (canGoNext) {
    if (state.steps + 1 == state.questionList.length) {
      confirm()
    } else {
      state.steps++
    }
  } else {
    uni.showToast({
      title: '请完成问卷内容填写！',
      icon: 'none'
    })
  }
}
const confirm = () => {
  const params = {
    clientId: 2,
    patientQuestionnaireAnswerVOs: []
  }
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answer = {
        id: state.questionInfo.id,
        userId: userInfo.value.userId,
        empi: currentId,
        creator: '',
        createTime: state.questionInfo.createTime,
        updateTime: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        questionnaireId: state.questionInfo.questionnaireId,
        questionId: val.id,
        questionnaireRecordId: state.questionInfo.questionnaireId,
        optionId: val.questionType == '单选' || val.questionType == '多选' ? val.option : '',
        content: val.questionType == '输入' ? val.inputText : val.value,
        extContent: val.questionType == '选择 + 输入' ? val.inputText : '',
        score: val.scores
      }
      params.patientQuestionnaireAnswerVOs.push(answer)
    })
  })
  uni.showLoading({
    title: '正在提交中...',
    mask: true
  })
  weight_save(params).then((res) => {
    if (res.code == 0) {
      userInfo.value.patientInfo.questionState = true
      store.commit('SET_USERINFO', userInfo.value)
      uni.hideLoading()
      uni.showToast({
        title: '问卷提交成功，即将进入体重管理方案',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.redirectTo({
              url: '/packA/pages/weightManage/scheme'
            })
          }, 2000)
        }
      })
    }
  })
}
</script>

<style lang="scss" scoped>
.body {
  height: 100%;
  // 步骤条样式
  ::v-deep .u-steps {
    align-items: center;
    height: 140rpx;
    background: #fff;
  }

  ::v-deep .uicon-checkmark {
    font-size: 24rpx !important;
  }

  ::v-deep .u-steps-item__line {
    left: 78.5px !important;
    width: 95px !important;
    height: 1rpx !important;
    background-color: #e5e6eb !important;
  }

  ::v-deep .u-text__value--content {
    color: #999 !important;
  }

  ::v-deep .u-steps-item__content {
    margin: 0 !important;
    margin-top: 16rpx !important;

    .u-text__value {
      font-size: 28rpx !important;
    }

    .u-text__value--main {
      color: #00d1b6;
    }

    .u-text__value--content {
      color: #999;
    }
  }

  .base_info {
    height: calc(100vh - 346rpx);
    padding: 24rpx 32rpx;
    overflow: auto;

    .topic {
      margin-bottom: 26rpx;
      font-size: 28rpx;
      font-weight: 400;
      color: #666;
    }

    .baseInfoBox {
      padding: 32rpx;
      background: #fff;
      border-radius: 16rpx;

      .box_title {
        margin-bottom: 24rpx;
        font-size: 36rpx;
        font-weight: 700;
        color: #222;
      }

      .cell {
        box-sizing: border-box;
        display: flex;
        align-items: center;
        justify-content: space-between;
        height: 108rpx;
        border-bottom: 1rpx solid #e5e6eb;

        .left {
          font-size: 30rpx;
          font-weight: 700;
          color: #222;
        }

        .right {
          display: flex;
          gap: 24rpx;
          justify-content: flex-end;
          font-size: 30rpx;
          font-weight: 400;
          color: #222;

          .form_input {
            text-align: right;
          }

          text {
            display: inline-block;
            width: 42rpx;
            text-align: left;
          }
        }
      }

      .question {
        margin-bottom: 40rpx;

        &:last-child {
          margin: 0;
        }

        .question_title {
          display: flex;
          align-items: center;
          margin-bottom: 24rpx;
          font-size: 32rpx;
          font-weight: 700;
          color: #222;

          .isMore {
            display: inline-block;
            width: 80rpx;
            height: 40rpx;
            margin-right: 6rpx;
            font-size: 24rpx;
            font-weight: 500;
            line-height: 40rpx;
            color: #fff;
            text-align: center;
            background: #5c8eff;
            border-radius: 4rpx;
          }
        }

        .answer {
          display: flex;
          flex-wrap: wrap;
          gap: 16rpx;
          justify-content: space-between;
          margin-top: 32rpx;

          .answer_item {
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            width: 48%;
            padding: 16rpx 24rpx;
            margin-bottom: 8rpx;
            font-size: 30rpx;
            font-weight: 400;
            color: #222;
            text-align: center;
            background: #fafafa;
            border: 1rpx solid #fafafa;
            border-radius: 8rpx;
            transform: rotateZ(360deg);

            &.on {
              font-size: 30rpx;
              font-weight: 500;
              color: #00d1b6;
              background: rgb(0 209 182 / 10%);
              border: 1rpx solid #00d1b6;
              border-radius: 8rpx;
            }

            &.disabled {
              color: #999;
              background: #f5f5f5;
            }
          }

          .w100 {
            width: 100%;
          }
        }
      }
    }
  }

  .fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 10;
    box-sizing: border-box;
    display: flex;
    gap: 24rpx;
    justify-content: space-between;
    width: 100%;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    background: #fff;
    border-top: 1rpx solid #e5e6eb;

    .pre_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #00d1b6;
      background: #fff;
      border: 1rpx solid #00d1b6;
      border-radius: 44rpx;
    }

    .next_btn {
      width: 100%;
      font-size: 32rpx;
      font-weight: 700;
      color: #fff;
      background: #00d1b6;
      border-radius: 44rpx;
    }
  }
}
</style>
